package cheme.ProcessModel.Interpreter.Parsers;

import cheme.Interpreter.Parser.Parser;
import syntaxtree.Node;

public class QuantityParser extends AbstractFieldParser
{
	@Override
	public String prepareString(String text)
	{
		if(text.trim().isEmpty())
		{
			return super.prepareString("?");
		}
		else
		{
			/*
			 * Note that the "Parser.SingleNumericFactor();" method is a little too finicky
			 * on what constitutes a floating point number. It excludes "1." as a number.
			 * It also yields that not an exception that this code can catch, but some 
			 * gobbly-gook parser error string.
			 * 
			 * I've rigged a less than desireable work around for now. It allows
			 * the types of values desired and maintains the error message status quo.
			 * 
			 * The goal is to compensate for a numeric string is it is approximately that.
			 * 
			 * If it is totally buggered, just let it go.
			 */
			
			try
			{
				String candidate = "0" + text;
				
				if(!candidate.contains("."))
				{
					candidate += ".0";
				}
				else if(candidate.charAt(candidate.length() - 1) == '.')
				{
					candidate += "0";
				}

				double test = Double.parseDouble(candidate); //added the constraint that the string parse to a numeric value.
				
				/*
				 * If the candidate turns out to be a valid numeric string, keep it
				 */
				text = candidate;
				
				//System.out.println(text);
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			
			return "[" + text + "]";
			
//			return super.prepareString(text);
		}
	}
	
	public boolean syntaxIsValid(String text)
	{
		return parse(text) != null;
	}
	
	protected Node internalParse()
	{
		try
		{
			
			
			/*
			 * This parse is finicky and can yield a non-exception error string 
			 * that the current error reporting mechanism (which depends on catching
			 * exceptions, as below) cannot detect and manage.
			 * 
			 *  Workarounds are instituted in the QuantityParser.prepareString(
			 *  String text) method above.
			 */
			return Parser.SingleNumericFactor();
		}
		catch(Exception e)
		{
			//System.out.println(e.getMessage());
			throw new Error("This quantity contains an error. Quanities are specified as decimal numbers such as \"0.5\"");
		}
	}
}